package com.liuning.security;

import cn.hutool.core.util.StrUtil;
import com.liuning.Utils.JwtUtils;
import com.liuning.entity.SysUser;
import com.liuning.service.SysUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserDetailServiceImpl userDetailService;

    @Autowired
    SysUserService sysUserService;


    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取jwt
        String jwt = request.getHeader(jwtUtils.getHeader());
        //判断是否有jwt
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request,response);
            return;
        }
        //存在jwt的话，解析jwt
        Claims claims = jwtUtils.getClaimsByToken(jwt);
        //token不合法，可能被篡改过
        if (claims == null) {
            throw new JwtException("token 异常");
        }
        //token过期
        if (jwtUtils.isTokenExpired(claims)) {
            throw new JwtException("token已过期");
        }
        //token合法的情况
        //因为之前在JwtUtils中生成token时设置了subject中的username
        String username = claims.getSubject();
        //获取用户id
        SysUser sysUser = sysUserService.getByUsername(username);

        //获取用户的权限
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,null,userDetailService.getUserAuthority(sysUser.getId()));
        //设置上下文的认证主体
        SecurityContextHolder.getContext().setAuthentication(token);
        //自动登录后继续执行
        chain.doFilter(request,response);
    }
}
